package com.kaikeba.wx.controller;

import com.kaikeba.bean.Courier;
import com.kaikeba.bean.Message;
import com.kaikeba.bean.User;
import com.kaikeba.mvc.ResponseBody;
import com.kaikeba.service.CourierService;
import com.kaikeba.service.UserService;
import com.kaikeba.util.JSONUtil;
import com.kaikeba.util.RandomUtil;
import com.kaikeba.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class UserController {
    @ResponseBody("/wx/loginSms.do")
    public String sendSms(HttpServletRequest request, HttpServletResponse response){
        String userPhone = request.getParameter("userPhone");
        //String code = RandomUtil.getCode()+"";
        //boolean flag = SMSUtil.loginSMS(userPhone, code);
        String code = "123456";
        boolean flag = true;
        Message msg = new Message();
        if(flag){
            //短信发送成功
            msg.setStatus(0);
            msg.setResult("验证码已发送,请查收!");
        }else{
            //短信发送失败
            msg.setStatus(1);
            msg.setResult("验证码下发失败,请检查手机号或稍后再试");
        }
        UserUtil.setLoginSms(request.getSession(),userPhone,code);

        String json = JSONUtil.toJSON(msg);
        return json;
    }
    @ResponseBody("/wx/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){
        String userPhone = request.getParameter("userPhone");
        String userCode = request.getParameter("code");
        String sysCode = UserUtil.getLoginSms(request.getSession(), userPhone);
        Message msg = new Message();
        if(sysCode == null){
            //这个手机号未获取短信
            msg.setStatus(-1);
            msg.setResult("手机号码未获取短信");
        }else if(sysCode.equals(userCode)){
            //这里手机号码和短信一致 , 登陆成功
            //TODO 这个判断应替换为快递员表格查询手机号的结果
            User user = new User();
            Courier courier = CourierService.findByPhone(userPhone);
            if(courier!=null){
                //快递员
                user.setUser(false);
                user.setUsername(courier.getUsername());
                user.setPassword(courier.getPassword());
                user.setNumber(courier.getNumber());
                user.setId(courier.getId());
                msg.setStatus(1);
                //更新登录时间与IP
                Date date = new Date();
                String ip = request.getRemoteAddr();
                CourierService.updateLoginTimeAndIP(userPhone,date,ip);
                msg.setResult("快递员身份登录！");
            }else{
                //用户
                User u = UserService.findByPhone(userPhone);
                user = u;
                msg.setStatus(0);
                msg.setResult("登录成功！");
                //  如果数据库中为空，应进行默认信息注册录入。
                if (user==null){
                    int num = RandomUtil.getCode();
                    u = new User("未注册的黑户","懒汉_"+num,userPhone,userPhone);
                    boolean b = UserService.insert(u);
                    if (b==true) {
                        user = UserService.findByPhone(userPhone);
                        msg.setResult("注册成功确保安全，首次登录请修改信息！");
                    } else {
                        msg.setStatus(-1);
                        msg.setResult("注册失败，请重试！");
                    }
                }
                //更新登录时间与IP
                Date date = new Date();
                String ip = request.getRemoteAddr();
                UserService.updateLoginTimeAndIP(userPhone,date,ip);
                user.setUser(true);
            }
            user.setUserPhone(userPhone);
            UserUtil.setWxUser(request.getSession(),user);
        }else{
            //这里是验证码不一致 , 登陆失败
            msg.setStatus(-2);
            msg.setResult("验证码不一致,请检查");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }
    @ResponseBody("/wx/update.do")
    public String update(HttpServletRequest request, HttpServletResponse response){
        String newPhone = request.getParameter("newPhone");
        String userCode = request.getParameter("code");
        String newName = request.getParameter("newName");
        String newPassword = request.getParameter("password");
        String sysCode = UserUtil.getLoginSms(request.getSession(), newPhone);
        User wxUser = UserUtil.getWxUser(request.getSession());
        Message msg = new Message();
        if(sysCode == null){
            //这个手机号未获取短信
            msg.setStatus(-1);
            msg.setResult("手机号码未获取短信");
        }else if(sysCode.equals(userCode)){
            //这里手机号码和短信一致 , 成功
            //依据库中的信息进行判断身份修改
            if(!wxUser.isUser()){
                //快递员
                Courier newCourier = new Courier(wxUser.getNumber(),newName,newPhone,newPassword==null?wxUser.getPassword():newPassword);
                boolean update = CourierService.update(wxUser.getId(), newCourier);
                if (update){
                    msg.setStatus(1);
                    msg.setResult("快递员身份修改成功！");
                }else {
                    msg.setStatus(0);
                }
                //更新登录时间与IP
               /* Date date = new Date();
                String ip = request.getRemoteAddr();
                CourierService.updateLoginTimeAndIP(userPhone,date,ip);*/
            }else{
                //用户
                User newUser = new User(wxUser.getNumber(), newName, newPhone,newPassword==null?wxUser.getPassword():newPassword);
                boolean update = UserService.update(wxUser.getId(), newUser);
                if (update){
                    msg.setStatus(1);
                    msg.setResult("用户修改成功！");
                }else {
                    msg.setStatus(0);
                }

            }
            //更新session中的wxUser
            if (msg.getStatus()==1){
                wxUser.setUsername(newName);
                wxUser.setUserPhone(newPhone);
                wxUser.setPassword(newPassword==null?wxUser.getPassword():newPassword);
            }
            UserUtil.setWxUser(request.getSession(),wxUser);
        }else{
            //这里是验证码不一致 , 登陆失败
            msg.setStatus(-2);
            msg.setResult("验证码不一致,请检查");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }
    @ResponseBody("/wx/userInfo.do")
    public String userInfo(HttpServletRequest request, HttpServletResponse response){
        User user = UserUtil.getWxUser(request.getSession());
        boolean isUser = user.isUser();
        Message msg = new Message();
        if(isUser)
            msg.setStatus(0);
        else
            msg.setStatus(1);
        msg.setResult(user.getUserPhone());
        String json = JSONUtil.toJSON(msg);
        return json;
    }
    @ResponseBody("/wx/getUser.do")
    public String getUser(HttpServletRequest request, HttpServletResponse response){
        //取出登录用户的信息
        User user = UserUtil.getWxUser(request.getSession());
        Message msg = new Message();
        if(user.getUsername().indexOf("懒汉_")==0) {
            msg.setStatus(1);
        } else{
            msg.setStatus(0);
        }
        msg.setData(user);
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/logout.do")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        //1.    销毁session
        request.getSession().invalidate();
        //2.    给客户端回复消息
        Message msg = new Message(0);
        return JSONUtil.toJSON(msg);
    }
}
